package com.hotacorp.opencloud.gateway.filter;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.setResponseStatus;

import java.io.UnsupportedEncodingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSONObject;
import com.hotacorp.opencloud.common.commdata.Constants;
import com.hotacorp.opencloud.common.commdata.Result;
import com.hotacorp.opencloud.gateway.feign.TenantFeignClient;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
 * 多租户处理全局过滤器，
 */
@Component
public class TenantFilter implements GlobalFilter, Ordered {

	@Autowired
	@Lazy
	private TenantFeignClient tenantFeignClient;
	
	@Override
	public int getOrder() {
		return NettyWriteResponseFilter.HIGHEST_PRECEDENCE + 999;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		//Result<Long> ddd = tenantFeignClient.getTokenInfo(exchange.getRequest().getURI().getHost());
		Result<Long> ddd = tenantFeignClient.getTokenInfo(exchange.getRequest().getHeaders().getHost().getHostString());
		if (ddd.getCode() == 0) {//调用成功
			ServerHttpRequest request = exchange.getRequest().mutate().header(Constants.TENANT_ID_HEAD, new String[] {String.valueOf(ddd.getData())}).build();
			return chain.filter(exchange.mutate().request(request).build());
		} else {
			setResponseStatus(exchange, HttpStatus.NOT_ACCEPTABLE);
            Flux<DataBuffer> bodyFlux = genDB(exchange, HttpStatus.NOT_ACCEPTABLE.value(), HttpStatus.NOT_ACCEPTABLE.getReasonPhrase());
            
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
            return exchange.getResponse().writeWith(bodyFlux).then(Mono.fromRunnable(() ->{exchange.getResponse().setComplete();}));
		}
	}

	private Flux<DataBuffer> genDB(ServerWebExchange exchange, int code, String msg) {
		Result<String> ddddd = new Result<String>("", code, msg);
		String string = JSONObject.toJSONString(ddddd);
		byte[] bodyStr = new byte[0];
		try {
			bodyStr = string.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		DataBufferFactory sss= exchange.getResponse().bufferFactory();
		DataBuffer bodyDataBuffer = sss.wrap(bodyStr);
        Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer);
        return bodyFlux;
	}

}
